import React, { FC, useEffect, useRef, useState } from 'react';
import './index.less';
import { useParams, useRequest } from 'umi';
import * as API from '@/services';
import { KfModal, useKeepAliveContext } from 'kf-web-library';
import { deleteJournalSubscribePlan, disableJournalSubscribePlan, enableJournalSubscribePlan, queryJournalSubscribePlans } from '@/services';
import { Button, Card, List, message, Space, Typography } from 'antd';
import { ProList } from '@ant-design/pro-components';
import JournalTempDocForm from '@/pages/biz/Journal/components/JournalTempDocForm';
import MallProductSubscribePlanQuickForm from './components/QuickForm';
import numeral from 'numeral';
import classNames from 'classnames';

interface MallProductSubscribePlanProps {}

/**
 * 订阅计划 页面
 */
const MallProductSubscribePlan: FC<MallProductSubscribePlanProps> = (props) => {
  const { journalId } = useParams();
  const { updateTab } = useKeepAliveContext() || {};
  /** 当前路由路径 **/
  const currentRoutePathRef = useRef<string>(location.pathname);

  const [createOpen, setCreateOpen] = useState(false);
  const [modifyOpenId, setModifyOpenId] = useState<API.EntityId | undefined>(undefined);

  const journalReq = useRequest(() => API.queryJournal(journalId!), {
    ready: !!journalId,
    onSuccess: (res) => {
      updateTab?.(location.pathname, {
        name: `《${res?.journalNameCn}》的订阅计划`
      });
    },
  });

  const journalName = journalReq?.data?.journalNameCn;


  const plansReq = useRequest(
    () =>
      API.queryJournalSubscribePlans({
        journalId,
        pageSize: 1000,
      }),
    {
      ready: !!journalId,
    },
  );

  const plans = (plansReq.data || []).map((plan) => {
    return {
      className: classNames('mpsp-card', {
        'mpsp-card-disabled': !plan.enable,
      }),
      id: plan.id,
      title: plan.planCode,
      avatar: 'https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg',
      actions: [
        plan.enable ? (
          <a
            onClick={() => {
              KfModal.confirm('禁用', plan.planName as string, () => {
                API.disableJournalSubscribePlan(plan.id!).then((res) => {
                  if (res.flag) {
                    message.info('禁用成功');
                    plansReq.refresh();
                  }
                });
              });
            }}
          >
            <Typography.Text type="danger">禁用</Typography.Text>
          </a>
        ) : (
          <a
            onClick={() => {
              KfModal.confirm('启用', plan.planName as string, () => {
                API.enableJournalSubscribePlan(plan.id!).then((res) => {
                  if (res.flag) {
                    message.info('启用成功');
                    plansReq.refresh();
                  }
                });
              });
            }}
          >
            <Typography.Text type="success">启用</Typography.Text>
          </a>
        ),
        <a
          key="run"
          onClick={() => {
            setModifyOpenId(plan.id);
          }}
        >
          编辑
        </a>,
        <a
          onClick={() => {
            KfModal.confirm('删除', plan.planName as string, () => {
              API.deleteJournalSubscribePlan(plan.id!).then((res) => {
                if (res.flag) {
                  message.info('删除成功');
                  plansReq.refresh();
                }
              });
            });
          }}
        >
          删除
        </a>,
      ],
      content: (
        <div
          style={{
            flex: 1,
          }}
        >
          <div>
            <h2>{plan.planName}</h2>
            <div>套餐定价: ￥{numeral(plan.totalPrice / 100).format('0.00')}</div>
            <div>包含期数: {plan.issueCount}</div>
            <div style={{ opacity: 0.5 }}>每期单价: ￥{numeral(plan.totalPrice / plan.issueCount / 100).format('0.00')}</div>
          </div>
        </div>
      ),
    };
  });

  return (
    <div className={'mall-product-subscribe-plan-container'}>
      <ProList<any>
        ghost={false}
        itemCardProps={{
          ghost: false,
          bodyStyle: {
            padding: '0 12px 12px 12px',
          },
        }}
        pagination={false}
        showActions="hover"
        rowSelection={{}}
        grid={{ gutter: 16, column: 6 }}
        onItem={(record: any) => {
          return {
            onMouseEnter: () => {
              console.log(record);
            },
            onClick: () => {
              console.log(record);
            },
          };
        }}
        metas={{
          title: {},
          subTitle: {},
          type: {},
          avatar: {},
          content: {},
          actions: {
            cardActionProps: 'extra',
          },
        }}
        toolbar={{
          actions: [
            <Button type="primary" key="primary" onClick={() => setCreateOpen(true)}>
              新建订阅套餐
            </Button>,
          ],
        }}
        headerTitle={`《${journalName}》的订阅套餐列表`}
        dataSource={plans}
        rowKey={(row) => row.id}
        rowClassName={(row) => {
          return row.className;
        }}
      />

      {(modifyOpenId || createOpen) && (
        <KfModal
          title={`订阅计划-${createOpen ? '创建' : '编辑'}`}
          open={true}
          destroyOnClose={true}
          onCancel={() => {
            setModifyOpenId(undefined);
            setCreateOpen(false);
          }}
          onSubmitted={() => {
            plansReq.refresh();
          }}
          width={700}
        >
          <MallProductSubscribePlanQuickForm bizId={modifyOpenId} journalId={journalId} formType={createOpen ? 'create' : 'modify'} />
        </KfModal>
      )}
    </div>
  );
};

export default MallProductSubscribePlan;
